﻿var addcontactGrid = addcontactGrid || {};
var isGridLoadFirstime = true;
var initialFilter = true;

addcontactGrid = function () {
    var gridInEditMode = false;
    var addcontactDropDownChanged = false;
    var addcontactDataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/AddContact/GetAddContacts",
                type: "get",
                cache: false,
                dataType: "json",

            },
            create: {
                url: "/AddContact/CreateAddContact",
                type: 'POST',
                dataType: "json",
                contentType: "application/JSON"

            },
            update: {
                url: "/AddContact/UpdateAddContact",
                type: 'POST',
                dataType: "json",
                contentType: "application/JSON"
            },
            destroy: {
                url: "/AddContact/DeleteAddContact",
                type: "POST",
                dataType: "json",
                contentType: "application/JSON"
            },
            parameterMap: function (options) {
                return kendo.stringify(options); // kendo.stringify serializes to JSON string
            }
        },

        pageSize: 10,
        schema: {
            model: {
                id: "id",
                fields: {
                    id: {
                        editable: false, nullable: true,
                        type: "int"
                    },
                    name: {
                        type: "string",
                        hidden: true,
                        editable: false
                    },
                    SavedResult: {
                        type: "string",
                        defaultValue: ""
                    },
                    firstName: {
                        type: "string",
                        hidden: true,

                    },
                    lastName: {
                        type: "string",
                        hidden: true
                    },
                    userId:
                        {
                            type: "int",
                            defaultValue: 0
                        },

                    CreatedUser: {

                        type: "string",
                        defaultValue: $('#userLoggedIn').val()
                        // defaultValue:'dan'


                    },

                    startDate: {
                        type: "date",
                        editable: false
                    },
                    error: function (a) {
                        $('#addcontactGrid').data("kendoGrid").cancelChanges();
                    },
                }
            }
        },
        //serverPaging: true,
        //serverFiltering: true,
        //serverSorting: true,
        //filter: [

        //    {
        //        logic: "and",
        //        filters:[
        //      { field: "startDate", operator: "eq", value: '@DateTime.Now.ToShortDateString()', },
        //        { field: "CreatedUser", operator: "eq", value: '@ViewBag.UserName' }
        //        ]
        //    },
        //    ]

    });

    var company = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/ScratchPad/GetJustCompanyName/",
                type: "get",
                contentType: "application/json",
                dataType: "json"
            }
        }
    });
    var contactDetails = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/ScratchPad/GetContactDetail/",
                type: "get",
                contentType: "application/json",
                dataType: "json"
            }
        },
        requestEnd: function (a, b) {

        }

    });

    var contantType = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/AddContact/GetContactTypes/",
                type: "get",
                contentType: "application/json",
                dataType: "json"
            }
        }
    });
    var jobTitle = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/AddContact/GetJobTitles/",
                type: "get",
                contentType: "application/json",
                dataType: "json"
            }
        }
    });

    var department = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/AddContact/GetDepartments/",
                type: "get",
                contentType: "application/json",
                dataType: "json"
            }
        }
    });


    return {
        addcontactDataSource: addcontactDataSource,
        company: company,
        contactDetails: contactDetails,
        contantType: contantType,
        jobTitle: jobTitle,
        department: department,

        addcontactDropDownChanged: addcontactDropDownChanged,
        gridInEditMode: gridInEditMode


    }

}();

$(function () {

    function dateTimeEditor(container, options) {
        $('<input data-text-field="' + options.field + '" data-value-field="' + options.field + '" data-bind="value:' + options.field + '" data-format="' + options.format + '"/>')
        .appendTo(container)
        .kendoDateTimePicker({});
    }
    $("#addcontactGrid").kendoGrid({
        dataSource: addcontactGrid.addcontactDataSource,
        dataBound: function (e) {

            debugger;
            if (isGridLoadFirstime == true) {
                isGridLoadFirstime = false;
                var count = 0; var IsItemFound = false;
                var dataList = e.sender.dataSource.data()
                for (var i = 0; i < dataList.length; i++) {
                    var list = dataList[i];
                    count++;
                    if (list.firstName == window.location.hash.substr(1).split(',')[1] &&
                        list.lastName == window.location.hash.substr(1).split(',')[0]) {
                        IsItemFound = true;
                        break;
                    }
                }

                if (IsItemFound == true) {
                    var pagesize = e.sender.dataSource.pageSize();
                    var currentpage = parseInt(count / pagesize) + 1;
                    e.sender.dataSource.page(currentpage);
                }

            }

            var rows = e.sender.tbody.children();

            for (var j = 0; j < rows.length; j++) {

                var row = $(rows[j]);
                var dataItem = e.sender.dataItem(row);
                debugger;

                if (dataItem.get("firstName") == window.location.hash.substr(1).split(',')[1] && dataItem.get("lastName") == window.location.hash.substr(1).split(',')[0]) {
                    row.addClass("someCssColorClass");
                }
            }
        },

        scrollable: true,
        height: "250px",
        toolbar: [{ name: "create", text: "Add a Contact" }, "excel"], //, "save", "cancel"],
        excel: {
            fileName: "ContactsExport.xlsx"
        },
        pageable: true,
        height: 500,
        columns: [

        { field: "details", title: "Details", filterable: false, width: "6em", template: "<a onclick=\"showDetails('#=id #', this);\"style=\"cursor: pointer;\"> View</a>" },
          { field: "company", title: "Company", filterable: false, width: "6em", template: "<a onclick=\"showCompany('#=id #' , this);\"style=\"cursor: pointer;\"> View</a>" },
          { field: "MSg", title: "MSG", filterable: false, width: "6em", template: "<a onclick=\"showCompanyMessages('#=id #', this);\"style=\"cursor: pointer;\"> View</a>" },
  { field: "CreatedUser", title: "Created User", filterable: true, width: "10em" },
      { field: "name", title: "FullName", width: "10em", filterable: true },

       { field: "firstName", title: "First Name", width: "10em", hidden: true, editable: true, filterable: false },
        { field: "lastName", title: "Last Name", width: "10em", hidden: true, editable: true, filterable: false },

    {
        field: "startDate", title: "Start Date", width: "10em", filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}", template: "#= kendo.toString(kendo.parseDate(startDate, 'yyyy-MM-dd'), 'MM/dd/yyyy') #",
        editor: dateTimeEditor,
        filterable: {
            ui: "datetimepicker"
        }
    },
      {
          title: "&nbsp;",
          width: "12em",
          // command: ["edit", "destroy"]
          command: [

              "edit",
              {
                  name: "Delete",


                  click: function (e) {

                      var tr = $(e.target).closest("tr"); //get the row for deletion
                      var dataItem = this.dataItem(tr); //get the row data so it can be referred later
                      //see what is coming in dataItem
                      //if (dataItem.QuestionAnswers.length > 0) {
                      //    $("#delValidation").addClass('in')
                      //}
                      //else {

                      deleteTopicConfirmation(e, this);
                      // }
                      return false;
                  }
              }
          ]
      }
        ],
        filterable: {
            extra: false,
            operators: {
                string: {
                    eq: "Is equal to",
                    neq: "Is not equal to",
                    contains: "Contains"
                }
            }
        },

        editable: "popup",
        sortable: {
            mode: "single",
            allowUnsort: false
        },
        selectable: true,

        edit: function (e) {
            e.container.find(".k-edit-label:nth-child(1)").hide();
            e.container.find(".k-edit-field:nth-child(2)").hide();
            e.container.find(".k-edit-label:nth-child(3)").hide();
            e.container.find(".k-edit-field:nth-child(4)").hide();
            e.container.find(".k-edit-label:nth-child(5)").hide();
            e.container.find(".k-edit-field:nth-child(6)").hide();
            //e.container.find(".k-edit-label:nth-child(7)").hide();
            //e.container.find(".k-edit-field:nth-child(8)").hide();
            e.container.find(".k-edit-label:nth-child(9)").hide();

            e.container.find(".k-edit-field:nth-child(10)").hide();



            addcontactGrid.gridInEditMode = true;
        },

        cancel: function () {
            addcontactGrid.gridInEditMode = false;
        }
    });
    //    $("#dirty").on("click", function (e) {
    //        debugger;
    //        alert(1);
    //        var grid = $('#addcontactGrid').data('kendoGrid');
    //        console.log("dirty", grid.dataSource.data());
    //        //filter: {
    //        //        field: "CreatorADGuid",
    //        //        operator: "eq",
    //        //        value: '@ViewBag.UserId'
    //        //},

    //        ///filter: [

    //        ////    {
    //        ////        logic: "and",
    //        ////        filters:[
    //        ////      { field: "startDate", operator: "eq", value: '@DateTime.Now.ToShortDateString()', },
    //        ////        { field: "CreatedUser", operator: "eq", value: '@ViewBag.UserName' }
    //        ////        ]
    //        ////    },
    //        ////    ]
    //        grid.dataSource.filter({
    //            logic: "and",
    //            filters:[
    //{ field:"CreatedUser",operator:"equals", value:'dan'}
    ////{ field: "startDate", operator:"equals", value: 'Mon May 02 2016'}

    //]
    //        });
    //        e.preventDefault();
    //    });
    //    $("#all").on("click", function (e) {
    //        debugger;
    //        alert(1);
    //        var grid = $('#addcontactGrid').data('kendoGrid');
    //        grid.dataSource.filter({});
    //        e.preventDefault();
    //    });

    $("#dirty").on("click", function (e) {
        $.ajax({
            url: "/AddContact/GetContactsByLoggedInUser",
            type: "get",
            cache: false,
            dataType: "json",
            success: function (data) {
                var grid = $('#addcontactGrid').getKendoGrid();
                $("#addcontactGrid").data("kendoGrid").dataSource.data(data);
            }
        });
        return false;

    });
    $("#all").on("click", function (e) {
        $.ajax({
            url: "/AddContact/GetAddContacts",
            type: "get",
            cache: false,
            dataType: "json",
            success: function (data) {
                var grid = $('#addcontactGrid').getKendoGrid();
                $("#addcontactGrid").data("kendoGrid").dataSource.data(data);
            }
        });
    });



    addcontactGrid.addcontactDataSource.bind("requestEnd", showSuccessMessage);
    function showSuccessMessage(e) {
        if (e.type === "update" || e.type === "create") {
            //alert(e.response.SavedResult);
            //console.log(e);
            //$(".SavedResult").html(e.response.SavedResult);
            if (e.response.SavedResult != "CREATED") {
                $(".SavedResult").html(e.response.SavedResult);
            }
            else {
                $(".SavedResult").html("");
                addcontactGrid.gridInEditMode = false;
                $("#saveConfirm").addClass('in');
                e.sender.read();
                debugger;
            }
            //var dataSource = $("#addcontactGrid").data("kendoGrid").dataSource;
            //var filters = dataSource.filter();
            //var allData = dataSource.data();
            //var query = new kendo.data.Query(allData);
            //var data = query.filter(filters).data;
        }
    }
    $(".close").click(function () {
        $(this).parent().removeClass('in');
    });

    //function createNew() {
    //    var grid = $("#grid").data("kendoGrid");
    //    grid.dataSource.filter({});
    //    grid.dataSource.sort({});
    //    //add record using Grid API
    //    grid.addRow();
    //}
    function deleteTopicConfirmation(e, widget) {
        var grid = $('#addcontactGrid').data("kendoGrid");
        deleteConfirmation(e, widget, grid);
    }

    function deleteConfirmation(e, widget, grid) {

        var currentRow = $(e.target).closest("tr"); //get the row for deletion

        var currentRowData = widget.dataItem(currentRow); //get the row data so it can be  referred later

        var kendoWindow = $("<div />").kendoWindow({

            title: "Confirmation",
            resizable: true,
            modal: true,
            width: "400px"
        });

        kendoWindow.data("kendoWindow")

            .content($("#delete-confirmation").html())

            .center().open();

        kendoWindow

            .find(".delete-confirm,.delete-cancel")
            .click(function () {
                if ($(this).hasClass("delete-confirm")) {

                    grid.dataSource.remove(currentRowData);

                    grid.dataSource.sync();

                }

                $(this).closest("[data-role=window]").kendoWindow("close");

            });

    }
    function companyDropDownEditor(container, options) {

        $('<input data-text-field="cpName" data-value-field="cpName" data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
            autoBind: false,
            dataSource: addcontactGrid.company

        });
    }
    function contactTypeDropDownEditor(container, options) {

        $('<input data-text-field="description" data-value-field="description"  data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
            autoBind: false,
            dataSource: addcontactGrid.contantType
        });
    }
    function jobTitleDropDownEditor(container, options) {

        $('<input data-text-field="code" data-value-field="code"  data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
            autoBind: false,
            dataSource: addcontactGrid.jobTitle

        });
    }
    function departmentDropDownEditor(container, options) {

        $('<input data-text-field="departmentCode" data-value-field="departmentCode"  data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
            autoBind: false,
            dataSource:
                addcontactGrid.department

        });
    }


    function contactAutoCompleteEditor(container, options) {
        $('<input data-text-field="name"  data-value-field="Name"  data-bind="value:' + options.field + '"/>')
        .appendTo(container)
        .kendoAutoComplete({
            autoBind: true,
            suggest: true,
            placeHolder: "enter caller name here",
            filter: "contains",
            //   index: 1,
            minLength: 1,
            dataSource: addcontactGrid.contactDetails
        });
    }


});


function SavePresentContact(id) {
    $.post("/AddContact/SaveIsPresentContact",
     {
         id: id,
     },
     function (data) {
         if (data == "SUCCESS") {
             $(".SavedResult").html(" ");
             $(".SavedResult").html("The Record were Saved");
             $('#addcontactGrid').data('kendoGrid').dataSource.read();
             $('#addcontactGrid').data('kendoGrid').refresh();
         }
     });
}

function DeletePresentContact(id) {
    $.post("/AddContact/DeletePresentContact",
    {
        id: id,
    },
    function (data) {
        if (data == "SUCCESS") {
            $(".SavedResult").html(" ");
            $(".SavedResult").html("Saving of the record is declined");
            $('#addcontactGrid').data('kendoGrid').dataSource.read();
            $('#addcontactGrid').data('kendoGrid').refresh();
        }
    });
}
